#!/bin/bash -e

BIN=$1

echo 
echo "####################################################################################"
echo "# A simple scripts to move aarch64 linux dynamic linked binary to android platform #"
echo "# version 1.0"
echo "# Author: kevin.zhao <zxq_yx_007@163.com>                                          #"
echo "####################################################################################"
echo 

usage()
{
	echo "Usage: $0 <dynamic linked binary file>"
	exit 1
}

[ -z "$BIN" ] && usage

ANDROID_EXEC_PREFIX=/data/local/tmp
DEST_DIR=$PWD/"$BIN".lib.d

ldd_output=$(mktemp)
echo "Analyzing depend library ..."
ldd "$BIN" > "$ldd_output"
grep -q ' => ' "$ldd_output"

[ ! -d $DEST_DIR ] && mkdir "$DEST_DIR"

# have dynamic linked library
if [ $? -eq 0 ]; then

	echo "Copy depended library to directory: $DEST_DIR ..."
	lib_dep=$(mktemp)
	grep ' => ' "$ldd_output" > "$lib_dep"
	while read i
		do 
		lib=$(echo "$i" | awk '{print $3}')
		echo "copying lib: $lib"
		cp -L "$lib" "$DEST_DIR"/$(basename "$lib")
	
	done < "$lib_dep"

fi

rm -f "$ldd_output" "$lib_dep"

interpreter=$(patchelf --print-interpreter "$BIN")
echo "interpreter is: $interpreter"
echo "Copy interpreter ..."
cp -L $interpreter "$DEST_DIR"/$(basename "$interpreter")

ld_library_path="$ANDROID_EXEC_PREFIX"/$(basename "$DEST_DIR")
patched_interpreter="$ld_library_path"/$(basename "$interpreter")

echo "patched interpreter is: $patched_interpreter"

echo "patching interpreter ..."
cp "$BIN" "$BIN".orig
patchelf --set-interpreter "$patched_interpreter" "$BIN"

echo "all done!"

echo "please do following on android devices: "
echo "step 1: copy $BIN and $DEST_DIR to $ANDROID_EXEC_PREFIX"
echo "step 2: cd $ANDROID_EXEC_PREFIX"
echo "step 3: export LD_LIBRARY_PATH=$ld_library_path"
echo "step 4: execute ./$BIN"

